﻿using System;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SpriteGame.Rendering;

namespace SpriteGame
{
    public class Ball:BaseSprite
    {
        protected double lifeTime;
        protected double maxlife = (double)TimeSpan.FromSeconds(5).Ticks;

        //bool canSave = true;

        public Ball() { }

        public Ball(Scene _parent, float _width, float _height, BodyType _type, Vector2 _position, float _rotation, String _texture)
        {
            lifeTime = 0;
            startRot = _rotation;
            startPos = _position;
            texture = _texture;
            width = _width;
            height = _height;
            BodyType = _type;


            //this object was created at runtime, load it immediatly
            LoadContent(_parent);
        }

        public override void LoadContent(Scene _parent)
        {
            parent = _parent;
            world = parent.World;


            parent = _parent;
            world = parent.World;

            if (width == 0 && height == 0)
            {
                Texture2D tex = TextureLibrary.GetTexture(texture);

                //body.
                width = tex.Width * 0.07f;
                height = tex.Height * 0.07f;
            }

            float r = width * 0.5f;

            CircleShape shape = new CircleShape(r);

            parent.LockPhysics();
            body = world.CreateBody();
            body.SetTransform(ref startPos, startRot);
            body.BodyType = this.BodyType;
            Fixture fixture = body.CreateFixture(shape, 0.12f);
            fixture.Restitution = 0.4f;
            parent.UnlockPhysics();
            body.FixtureList[0].OnSeparation += OnSeparation;

            body.UserData = this;
            isLoaded = true;
        }

        void OnSeparation(Fixture a, Fixture b)
        {
            AudioManager.SoundManager.PlaySound("BallBounce");

        }

        public override void Update(GameTime _time)
        {
            if (body.Position.X > 800 || body.Position.X < -800)
            {
                
            }

            lifeTime += (double)_time.ElapsedGameTime.Ticks;
            //parent.Particles.CreateExplosion(Position, 10);
            if (lifeTime > maxlife || body.Position.Y < -20 && body.LinearVelocity.Length() < 0.5f)
            {
                    parent.RemoveEntity(this);
            }
            base.Update(_time);
        }
    }
}
